﻿/**
* File: age.ui.age.js 
* Author: Angelo Gomez
* Date: 2011.09.08
*
* Copyright (c) 2011 Angelo Gomez
* 
*/
/// <reference path="jquery-1.5.1-vsdoc.js" />


(function ($) {

	// declare object names
	var _questionTextbox = 'questionText';
	var _questionId = 'questionId';
	var _choiceContainer = 'answersContainer';
	var _choiceCheckbox = 'isCorrect';
	var _choiceText = 'answerText';
	var _choiceExplanation = 'answerExplanation';
	var _questionTitleText = 'Question: ';
	var _answersTitleText = 'Answer (Options):';

	// TODO[P3]: Extend ability to set title texts from the view.

	/// QnaEntity
	var _data = {
		QuestionData:
		{
			QuestionID: 0,
			CategoryID: [4, 5],
			DifficultyLevel: 1,
			AccountID: 1,
			Question: 'What is this a test?',
			IsActive: true,
			FlagCode: 'V',
			GivenTime: 20,
			UserID: 1,
			AppLogID: 0
		},
		AnswerChoices:
		[
			{ AnswerID: 0, QuestionID: 0, Answer: 'Answer 1 from js', IsCorrect: true, AnswerExplanation: '', IsActive: false, OrderIndex: 0 },
			{ AnswerID: 0, QuestionID: 0, Answer: 'Answer 2 from js', IsCorrect: true, AnswerExplanation: 'Explanation 2', IsActive: true, OrderIndex: 1 },
			{ AnswerID: 0, QuestionID: 0, Answer: 'Answer 3 from js', IsCorrect: true, AnswerExplanation: '', IsActive: false, OrderIndex: 2 }
		],
		UserData:
		{
			UserID: 0,
			UserName: 'username',
			UserEmail: 'email@domain.com',
			AccountID: 2,
			DeviceType: 'PC00',
			DeviceDescription: 'IntelMac',
			OtherInfo: 'No other information for now.'
		},
		Error: ''
	};

	var questionpanel = '';

	/// $(selector).addQuestion(appendTo);
	/// is: Generates html objects (div) for the question.
	/// gets:	appendTo (string): Selector of the container that will store all the elements rendered.
	/// returns: none. 
	$.fn.addQuestion = function (appendTo) {

		var questionTitleText = document.createElement('div');
		$(questionTitleText).addClass('qContainer')
				.html('<h2>' + _questionTitleText + '</h2><span id="questionInstruction"><span>')
				.appendTo('#' + appendTo);

		var questionContainer = document.createElement('div');
		$(questionContainer).attr('id', 'questionContainer')
					.addClass('qContainer')
					.insertAfter(questionTitleText)
					.hide();

		var elementQuestionText = document.createElement('textarea');
		$(elementQuestionText).addClass('qtextbox')
					.attr('id', _questionTextbox)
					.attr('name', _questionTextbox)
					.attr('rows', '4')
					.attr('cols', '40')
					.val('')
					.appendTo(questionContainer);

		var elementHiddenQuestionId = document.createElement('input');
		$(elementHiddenQuestionId).attr('id', _questionId)
					.attr('name', _questionId)
					.attr('type', 'hidden')
					.val('0')
					.insertAfter(elementQuestionText);

		// TODO[P1]: Create more hidden elements to store more data.

		$(questionContainer).slideDown();
		$(elementQuestionText).focus();
	}

	/// $(selector).addChoice(appendTo);
	/// is: A function that renders objects for answer choices.
	/// gets:	appendTo (string): Selector of the container that will store all the elements rendered.
	/// returns: none.
	$.fn.addChoice = function (appendTo) {

		var firstLine = false;
		if ($('#answersContainer').size() <= 0) {
			firstLine = true;

			// Enter title:
			var answerTitleText = document.createElement('div');
			$(answerTitleText).html('<h2>' + _answersTitleText + '</h2><span id="answersInstruction"><span>')
					.addClass('qContainer')
					.appendTo('#' + appendTo);
		}
		// Find element to append the choice panel
		var line = document.createElement('div');
		$(line).attr('id', 'answersContainer')
					.addClass('qContainer')
					.appendTo('#' + appendTo)
					.css('display', 'block')
					.hide();

		//if (firstLine) $(line).html('<h2>Answer Choices:</h2>');

		var firstCol = document.createElement('div');
		$(firstCol).addClass('qCheckboxPanel')
					.appendTo(line);

		var secondCol = document.createElement('div');
		$(secondCol).addClass('qTextEntryPanel')
					.appendTo(line);


		var thirdCol = document.createElement('div');
		$(thirdCol).addClass('qEditPanel')
					.appendTo(line)


		var elementCheckboxIsCorrect = document.createElement('input');
		$(elementCheckboxIsCorrect).attr('type', 'checkbox')
					.attr('id', _choiceCheckbox)
					.attr('checked', false)
					.addClass('qcheckbox')
					.attr('name', _choiceCheckbox)
					.val('28')
					.appendTo(firstCol)
					.change(function () {
						$(elementTextareaExplanation).toggle();
						$(elementExplanationHeader).slideToggle();
					});

		var elementTextareaAnswer = document.createElement('textarea');
		$(elementTextareaAnswer).addClass('qtextbox')
					.attr('id', _choiceText)
					.attr('name', _choiceText)
					.attr('rows', '2')
					.attr('cols', '30')
					.val('')
					.appendTo(secondCol);

		var elementTextareaExplanation = document.createElement('textarea');
		$(elementTextareaExplanation).addClass('qtextbox')
					.attr('id', _choiceExplanation)
					.attr('name', _choiceExplanation)
					.attr('rows', '2')
					.attr('cols', '30')
					.val('')
					.appendTo(secondCol)
					.hide();
		var elementExplanationHeader = document.createElement('div');
		$(elementExplanationHeader).html('Explain why this answer choice is correct: (optional)')
				.attr('id', 'explanationHeader')
				.insertBefore(elementTextareaExplanation)
				.hide();

		if (!firstLine) {
			var elementDeleteButton = document.createElement('input');
			$(elementDeleteButton).addClass('qButton')
					.addClass('qDeleteButton')
					.addClass('qEditElement')
					.attr('type', 'button')
					.attr('id', 'deleteButton')
					.attr('name', 'deleteButton')
					.val('Delete')
					.appendTo(thirdCol)
					.click(function () {
						$(line).remove();
					})
					.hide();
		}


		$(line).slideDown();
		$(elementTextareaAnswer).focus();

	}

	/// $(selector).jsonStringify(obj);
	/// is: Alternative to JSON.stringify function. Serializes an object to a JSON string.
	/// gets:	obj (Object): A class entity.
	/// returns: String JSON ready to be transmitted.  
	$.fn.jsonStringify = function (obj) {

		// TODO[P1]: Apply escape characters to double quoates ("), single quotes(') and commas (,) on return strings.
		var t = typeof (obj);
		if (t != "object" || obj === null) {
			// simple data type  
			if (t == "string") obj = '"' + obj + '"';
			return String(obj);
		}
		else {
			// recurse array or object  
			var n, v, json = [], arr = (obj && obj.constructor == Array);
			for (n in obj) {
				v = obj[n]; t = typeof (v);

				if (t == "string") v = '"' + v + '"';
				else if (t == "object" && v !== null) v = $(document).jsonStringify(v);

				json.push((arr ? "" : '"' + n + '":') + String(v));
			}
			return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
		}
	}

	/// $(selector).bindQnaForm(options);
	/// is: A function that binds form elements to the object entity corresponding to Age.Qna.Entity.QnaEntity. 
	/// gets: options (object) >>
	///				>> stringify (bool): Return a string or not.
	///				>> containerId (string): ID of the container that holds the elements to be binded.
	///				>> debug (bool): Activated for debugging.
	///				>> model (QnaModel.QnaEntity): Reference object from age.ui.qna.model.js
	/// returns: Object QnaModel.QnaEntity from age.ui.qna.model.js
	$.fn.bindQnaForm = function (options) {
		var defaults = {
			stringify: true,
			containerId: 'form',
			debug: false,
			model: QnaModel.QnaEntity
		};

		var options = $.extend(defaults, options);

		return this.each(function () {

			var formSelector = options.containerId;
			if (formSelector.substring(0, 1) != '#') formSelector = '#' + options.containerId;

			//TODO[P1]: Check if form is valid.

			//model = QnaModel.QnaEntity; // Take from age.ui.qna.model.js // TODO[P2]: Make sure references are available.

			// 1: Bind question data
			options.model.QuestionData.AccountID = 0;
			options.model.QuestionData.AppLogID = 0;
			//options.model.QuestionData.CategoryID = [4, 5];
			options.model.QuestionData.DifficultyLevel = 1;
			options.model.QuestionData.FlagCode = 'V';
			options.model.QuestionData.GivenTime = 10;
			options.model.QuestionData.IsActive = true;
			options.model.QuestionData.Question = $(formSelector).find('textarea[name="' + _questionTextbox + '"]').val(); //_questionTextbox
			options.model.QuestionData.QuestionID = $(formSelector).find('input[name="' + _questionId + '"]').val();
			options.model.QuestionData.UserID = 1; // TODO[P1]: Get userid from cookie or session?

			// 2: Bind answer choices

			// Empty any existing assignments to make way for the new assignments.
			if (options.model.AnswerChoices.length > 0) options.model.AnswerChoices.splice(0, options.model.AnswerChoices.length); ;

			// Traverse through all text areas
			$('div#' + _choiceContainer).each(function (index) {

				options.model.AnswerChoices.push({
					AnswerID: 0,
					QuestionID: 0,
					Answer: $(this).find('textarea[name^="' + _choiceText + '"]').val(),
					IsCorrect: $(this).find('input[name^="' + _choiceCheckbox + '"]').is(':checked'),
					AnswerExplanation: $(this).find('textarea[name^="' + _choiceExplanation + '"]').val(),
					IsActive: true,
					OrderIndex: index
				});

			});

			// 3: Bind user data and other information:

			if (options.debug) {
				alert(JSON.stringify(options.model)); // TODO[P3]: Investigate this if JSON.stringify works in older browsers.
			}

			return options.model;

		});
	};



})(jQuery);
